package com.ngkj.zmfptback.sys.filter;

import com.ngkj.zmfptback.sys.bean.OperationEntity;
import com.ngkj.zmfptback.sys.service.read.OperationReadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 获取到请求的url 查询数据库获取该url的相应权限
 * @author ChenHN
 * @since 2021/12/3 creation
 **/
@Component
@Slf4j
public class UrlFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {


    @Resource
    private OperationReadService operationReadService;

    /**
     *
     * @param object  FilterInvocation 可以获取到url
     * @return null 为不需要任何权限
     * @throws IllegalArgumentException
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        String[] split1 = requestUrl.split("\\?");
        requestUrl = split1[0];
        String[] split = requestUrl.split("/");
        List<String> urls = new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder("/");
        for (int i = 1; i < split.length-1; i++) {
            stringBuilder.append(split[i]+"/**");
            urls.add(stringBuilder.toString());
        }
        urls.add(requestUrl);
        List<String> roleCodes = operationReadService.getRolByUrl(urls);
        Collection<ConfigAttribute> configs = new ArrayList<>();
        for (String roleCode : roleCodes) {
            configs.add(new SecurityConfig("ROLE_"+roleCode));
        }

        return configs;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return
                FilterInvocation.class.isAssignableFrom(clazz);
    }
}
